<template>
  <div class="container">
    <h1>{{ isEdit ? "修改车位" : "新建车位" }}</h1>
    <hr style="border: 1px solid rgb(240, 240, 240)" />
    <span>基础信息</span>
    <div class="body">
      <div class="input">
        <div class="input-left">
          <span>区域名称</span>
        </div>
        <div class="input-right">
          <el-select
            v-model="selectedRegionName"
            placeholder="请选择区域名称"
            @change="onRegionNameChange"
          >
            <el-option
              v-for="region in uniqueRegions"
              :key="region.name"
              :label="region.name"
              :value="region.name"
            />
          </el-select>
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>区域编号</span>
        </div>
        <div class="input-right">
          <el-select
            v-model="selectedRegionNo"
            placeholder="请选择区域编号"
            :disabled="!filteredRegionNos.length"
          >
            <el-option
              v-for="no in filteredRegionNos"
              :key="no"
              :label="no"
              :value="no"
            />
          </el-select>
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>车位编号</span>
        </div>
        <div class="input-right">
          <el-input v-model="no" placeholder="请输入" />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>车位面积</span>
        </div>
        <div class="input-right">
          <el-input v-model="area" type="number" placeholder="请输入" />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>楼层</span>
        </div>
        <div class="input-right">
          <el-input v-model="floor" type="number" placeholder="请输入" />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>车位类型</span>
        </div>
        <div class="input-right">
          <el-radio-group v-model="type" placeholder="请选择">
            <el-radio value="1">产权车位</el-radio>
            <el-radio value="2">公共车位</el-radio>
          </el-radio-group>
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>车位状态</span>
        </div>
        <div class="input-right">
          <el-select v-model="status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>持有人</span>
        </div>
        <div class="input-right">
          <el-input v-model="owner" placeholder="请输入" />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>备注</span>
        </div>
        <div class="input-right">
          <el-input v-model="remark" :rows="5" type="textarea" />
        </div>
      </div>
      <div style="margin: 2rem 0 2rem 12rem">
        <el-button type="primary" @click="handleSubmit"
          >{{ isEdit ? "保存" : "提交" }}
        </el-button>
        <el-button type="default" @click="to('car/position')">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import to from "@/utils/to.js";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";

// 表单数据绑定
const selectedRegionName = ref(null); // 当前选中的区域名称
const selectedRegionNo = ref(null); // 当前选中的区域编号
const regionData = ref([]); // 原始区域数据
const uniqueRegions = ref([]); // 不重复的区域名称列表
const filteredRegionNos = ref([]); // 根据选择的区域名称筛选出的编号列表
const region = ref("");
const no = ref("");
const area = ref(0);
const floor = ref(1);
const type = ref("");
const status = ref("");
const owner = ref("");
const remark = ref("");
const options = [
  { value: "1", label: "闲置" },
  { value: "2", label: "自用" },
  { value: "3", label: "租赁" },
  { value: "4", label: "借出" },
  { value: "5", label: "其他" },
];

// 编辑标识
const isEdit = ref(false);

// 获取 URL 参数
const route = useRoute();
const id = route.params.id || route.query.id;

// 获取区域数据
const fetchRegions = async () => {
  try {
    const response = await axios.get(
      "http://localhost:8080/vehicleRegion/selectByName",
      {
        headers: {
          Authorization: localStorage.getItem("token"),
        },
        params: {
          pageNum: 1,
          pageSize: 100,
          name: region.value || "",
          status: status.value || "",
        },
      }
    );
    regionData.value = response.data.records; // 假设接口返回的数据是一个数组
    processRegionData();
  } catch (error) {
    console.error("获取区域数据失败", error);
    ElMessage.error("区域数据加载失败，请稍后重试");
  }
};

// 处理区域数据
const processRegionData = () => {
  const regionMap = new Map();
  regionData.value.forEach((region) => {
    if (!regionMap.has(region.name)) {
      regionMap.set(region.name, []);
    }
    regionMap.get(region.name).push(region.no);
  });
  uniqueRegions.value = Array.from(regionMap.keys()).map((name) => ({
    name,
    nos: regionMap.get(name),
  }));
};

// 当选择区域名称时，动态更新区域编号
const onRegionNameChange = () => {
  const selectedRegion = uniqueRegions.value.find(
    (region) => region.name === selectedRegionName.value
  );
  filteredRegionNos.value = selectedRegion ? selectedRegion.nos : [];
};

// 加载车位数据（编辑时填充表单）
const fetchPositionData = async () => {
  if (!id) return;

  try {
    const response = await axios.get(
      "http://localhost:8080/vehiclePosition/selectById",
      {
        headers: {
          Authorization: localStorage.getItem("token"),
        },
        params: { id },
      }
    );
    const data = response.data.data;
    if (data) {
      // 拆分区域字符串
      const regionParts = data.region.split("-");
      selectedRegionName.value = regionParts[0]; // 区域名称
      selectedRegionNo.value = regionParts[1]; // 区域编号
      no.value = data.no;
      area.value = data.area;
      floor.value = data.floor;
      type.value = data.type;
      status.value = data.status;
      owner.value = data.owner;
      remark.value = data.remark;
      isEdit.value = true; // 设置为编辑模式
      onRegionNameChange(); // 更新区域编号列表
    }
  } catch (error) {
    console.error("获取车位数据失败", error);
    ElMessage.error("车位数据加载失败");
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!selectedRegionName.value || !selectedRegionNo.value) {
    ElMessage.warning("请填写完整的区域信息");
    return;
  }

  const region = `${selectedRegionName.value}-${selectedRegionNo.value}`;

  const payload = {
    region: region,
    no: no.value,
    area: area.value,
    floor: floor.value,
    type: type.value,
    status: status.value,
    owner: owner.value,
    remark: remark.value,
  };

  try {
    let response;
    if (isEdit.value) {
      response = await axios.put(
        "http://localhost:8080/vehiclePosition/update",
        {
          id: id,
          ...payload,
        },
        {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        }
      );
    } else {
      response = await axios.post(
        "http://localhost:8080/vehiclePosition/PositionAdd",
        payload,
        {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        }
      );
    }

    if (response.status === 200) {
      ElMessage.success(isEdit.value ? "车位修改成功" : "车位添加成功");
      setTimeout(() => {
        to("car/position");
      }, 2000);
    }
  } catch (error) {
    console.error("车位操作失败", error);
    ElMessage.error("车位操作失败，请稍后重试");
  }
};

// 页面加载时获取区域数据
onMounted(() => {
  fetchRegions();
  fetchPositionData(); // 编辑时加载车位数据
});
</script>

<style scoped>
.container {
  background-color: white;
  height: auto;
  margin-top: 2rem;
  margin-bottom: 2rem;
}

h1 {
  font-size: 2rem;
  font-weight: 600;
  padding: 2rem 0 10px 4rem;
}

span {
  display: inline-block;
  font-size: 15px;
  margin: 1rem 2rem 1rem 0;
  line-height: 24px;
  width: 100px;
  text-align: right;
}

.body {
  display: grid;
  justify-content: center;
  align-items: center;
}

.input {
  display: flex;
  justify-content: center;
  align-items: center;
  width: auto;
}

.input-right {
  width: 300px;
}
</style>
